package com.erp.itm.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.erp.common.controller.BaseController;
import com.erp.common.domain.DictDO;
import com.erp.common.service.DictService;
import com.erp.common.utils.*;
import com.erp.itm.domain.*;
import com.erp.itm.service.*;
import com.erp.pro.domain.InstockDO;
import com.erp.system.domain.CompanyDO;
import com.erp.system.domain.DeptDO;
import com.erp.system.domain.UserDO;
import com.erp.system.service.CompanyService;
import com.erp.system.service.DeptService;
import com.erp.system.service.UserService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 项目管理
 * 
 * @author Eric
 * @email shiliang900713@163.com
 * @date 2019-07-17 20:36:10
 */
@Controller
@RequestMapping("/itm/project")
public class ProjectController extends BaseController {
	@Autowired
	private ProjectService projectService;

	@Autowired
	private ProjecttypeService projecttypeService;

	 @Autowired
	 private UserService userService;

	@Autowired
	private DeptService sysDeptService;

	@Autowired
	private DictService dictService;

	@Autowired
	private PaytypeService paytypeService;

	@Autowired
	private DeviceAmountService deviceAmountService;

	@Autowired
	private DeviceAmountTwoService deviceAmountTwoService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private ProjectFileService projectFileService;

	@Autowired
	private ProjectLogService projectLogService;
	@Autowired
	private ProjectUsersService projectUsersService;

	@Autowired
	private ProjectCustnameService projectCustnameService;

	@GetMapping()
	@RequiresPermissions("itm:project:project")
	String Project(){
		return "itm/project/project";
	}
	
	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询当前登录人的角色信息是管理层
		int mgrcount = userService.isManagerOrCeo(getUserId());
		if(mgrcount<=0) {
			params.put("createUserid",getUserId());
		}
		//查询列表数据
        Query query = new Query(params);
		List<ProjectDO> projectList = projectService.list(query);
		int total = projectService.count(query);
		PageUtils pageUtils = new PageUtils(projectList, total);
		return pageUtils;
	}


	@GetMapping("/add")
	String add(Model model){
		this.getInfo(model);
	    return "itm/project/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("itm:project:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ProjectDO project = projectService.get(id);
		//查询项目组成员
		getProjectGroup(id, project);
		model.addAttribute("project", project);
		this.getInfo(model);
	    return "itm/project/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("itm:project:add")
	public R save( ProjectDO project){
		UserDO user = ShiroUtils.getUser();
		project.setUserIdCreate(user.getUserId());
		project.setUserNameCreate(user.getName());
		project.setGmtCreate(new Date());
		project.setUserIdModified(user.getUserId());
		project.setUserNameModified(user.getName());
		project.setGmtModified(new Date());
		//获取部门信息
		DeptDO deptDO = sysDeptService.get(project.getDeptId());
		project.setDeptName(deptDO.getName());
		//项目负责人
		UserDO userDO = userService.get(project.getItmManagerId());
		project.setItmManagerName(userDO.getName());
		//项目类型
		ProjecttypeDO projecttypeDO = projecttypeService.get(project.getItmProTypeid());
		project.setItmProType(projecttypeDO.getName());

		CompanyDO companyDO = companyService.get(project.getComplanyId());
		project.setComplanyName(companyDO.getName());
		if(projectService.save(project)>0){
			//记录日志
			saveProjectLog(project,user,"新增项目");
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("itm:project:edit")
	public R update( ProjectDO project){

		UserDO user = ShiroUtils.getUser();
		project.setUserIdModified(user.getUserId());
		project.setUserNameModified(user.getName());
		project.setGmtModified(new Date());
		//获取部门信息
		DeptDO deptDO = sysDeptService.get(project.getDeptId());
		project.setDeptName(deptDO.getName());
		//项目负责人
		UserDO userDO = userService.get(project.getItmManagerId());
		project.setItmManagerName(userDO.getName());
		//项目类型
		ProjecttypeDO projecttypeDO = projecttypeService.get(project.getItmProTypeid());
		project.setItmProType(projecttypeDO.getName());

		CompanyDO companyDO = companyService.get(project.getComplanyId());
		project.setComplanyName(companyDO.getName());
		projectService.update(project);
		//记录日志
		saveProjectLog(project, user,"更新项目");
		return R.ok();
	}

	private void saveProjectLog(ProjectDO project, UserDO user,String message) {
		ProjectLogDO projectLogDO = new ProjectLogDO();
		projectLogDO.setGmtCreate(new Date());
		projectLogDO.setProjectId(project.getId());
		projectLogDO.setUserNameCreate(user.getName());
		projectLogDO.setUserIdCreate(user.getUserId());
		projectLogDO.setRemark(message);
		projectLogDO.setProjectName(project.getName());
		projectLogService.save(projectLogDO);
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("itm:project:remove")
	public R remove( Long id){
		if(projectService.remove(id)>0){
			//记录日志
			ProjectDO project = projectService.get(id);
			UserDO user = ShiroUtils.getUser();
			saveProjectLog(project, user,"终止项目");
			return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("itm:project:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		projectService.batchRemove(ids);
		return R.ok();
	}


	/**
	 * 添加商务信息
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/bissedit/{id}")
	String bissedit(@PathVariable("id") Long id,Model model){
		ProjectDO project = projectService.get(id);
		model.addAttribute("project", project);
		this.getInfo(model);
		//查询商务信息
		DeviceAmountDO deviceAmountDO = deviceAmountService.getProjectId(id);
		if(deviceAmountDO == null){
			deviceAmountDO = new DeviceAmountDO();
			deviceAmountDO.setProfitmargin("0%");
		}else{
			if(deviceAmountDO.getAllAmount() != null && deviceAmountDO.getAllAmount().compareTo(BigDecimal.ZERO) !=0){
				BigDecimal b =deviceAmountDO.getProfit().divide(deviceAmountDO.getAllAmount(),5);
				b= b.multiply(new BigDecimal(100));
				double promarg = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				deviceAmountDO.setProfitmargin(promarg+"%");
			}else{
				deviceAmountDO.setProfitmargin("0%");
			}
		}
		model.addAttribute("deviceAmount", deviceAmountDO);
		return "itm/project/bissadd";
	}


	/**
	 * 添加商务信息(二次)
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/bissedittwo/{id}")
	String bissedittwo(@PathVariable("id") Long id,Model model){
		ProjectDO project = projectService.get(id);
		model.addAttribute("project", project);
		this.getInfo(model);
		//查询商务信息
		DeviceAmountDO deviceAmountDO = deviceAmountService.getProjectId(id);
		if(deviceAmountDO == null){
			deviceAmountDO = new DeviceAmountDO();
			deviceAmountDO.setProfitmargin("0%");
		}else{
			if(deviceAmountDO.getAllAmount() != null && deviceAmountDO.getAllAmount().compareTo(BigDecimal.ZERO) !=0){
				BigDecimal b =deviceAmountDO.getProfit().divide(deviceAmountDO.getAllAmount(),5);
				b= b.multiply(new BigDecimal(100));
				double promarg = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				deviceAmountDO.setProfitmargin(promarg+"%");
			}else{
				deviceAmountDO.setProfitmargin("0%");
			}
		}
		model.addAttribute("deviceAmount", deviceAmountDO);

		DeviceAmountTwoDO deviceAmountTwoDO = deviceAmountTwoService.getProjectId(id);
		if(deviceAmountTwoDO == null){
			deviceAmountTwoDO = new DeviceAmountTwoDO();
			deviceAmountTwoDO.setProfitmargin("0%");
		}else{
			if(deviceAmountTwoDO.getAllAmount() != null && deviceAmountTwoDO.getAllAmount().compareTo(BigDecimal.ZERO) !=0){
				BigDecimal b =deviceAmountTwoDO.getProfit().divide(deviceAmountTwoDO.getAllAmount(),5);
				b= b.multiply(new BigDecimal(100));
				double promarg = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				deviceAmountTwoDO.setProfitmargin(promarg+"%");
			}else{
				deviceAmountTwoDO.setProfitmargin("0%");
			}
		}
		model.addAttribute("deviceAmountTwoDO", deviceAmountTwoDO);
		return "itm/project/bissaddtwo";
	}


	/**
	 * 完善商务信息
	 * @param project
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/bissupdate")
	public R bissupdate( ProjectDO project){
		savebiss(project,0);
		UserDO user = ShiroUtils.getUser();
		saveProjectLog(project, user,"第一次商务信息完善");
		return R.ok();
	}


	/**
	 * 完善商务信息（报价保存）
	 * @param project
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/bissupdateinfo")
	public R bissupdateinfo( ProjectDO project){
		savebiss(project,1);
		UserDO user = ShiroUtils.getUser();
		saveProjectLog(project, user,"第一次完善商务信息（报价保存）");
		return R.ok();
	}

	/**
	 * 保存销售填写的报价信息
	 * @param project
	 * @param flag
	 */
	public void savebiss(ProjectDO project,Integer flag){
		UserDO user = ShiroUtils.getUser();
		project.setUserIdModified(user.getUserId());
		project.setUserNameModified(user.getName());
		project.setGmtModified(new Date());
		//查询付款方式信息
		PaytypeDO paytypeDO = paytypeService.get(project.getPaytypeId());
		project.setPaytypeName(paytypeDO.getName());
		if(flag == 0){
			project.setStatus(3);
		}
		projectService.update(project);
		saveProjectLog(project, user,"修改项目为在建阶段");
		//查询是否已经存在
		//查询商务信息
		DeviceAmountDO deviceAmountDO = deviceAmountService.getProjectId(project.getId());
		if(deviceAmountDO == null){
			//保存合同金额信息
			DeviceAmountDO deviceAmount = project.getDeviceAmount();
			deviceAmount.setProjectId(project.getId());
			deviceAmountService.save(deviceAmount);
			saveProjectLog(project, user,"修改项目合同金额为："+deviceAmount);
		}else{
			//更新合同金额信息
			DeviceAmountDO deviceAmount = project.getDeviceAmount();
			deviceAmount.setId(deviceAmountDO.getId());
			deviceAmountService.update(deviceAmount);
			saveProjectLog(project, user,"修改项目合同金额为："+deviceAmount);
		}

	}


	/**
	 * 完善商务信息(二次确认)
	 * @param project
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/bissupdatetwo")
	public R bissupdatetwo( ProjectDO project){
		saveBissaddTwo(project);
		return R.ok();
	}

	private void saveBissaddTwo(ProjectDO project) {
		UserDO user = ShiroUtils.getUser();
		project.setUserIdModified(user.getUserId());
		project.setUserNameModified(user.getName());
		project.setGmtModified(new Date());
		//查询付款方式信息
		PaytypeDO paytypeDO = paytypeService.get(project.getPaytypeId());
		project.setPaytypeName(paytypeDO.getName());
		projectService.update(project);
		saveProjectLog(project, user,"完善商务信息(二次确认)");
		//查询是否已经存在
		//查询商务信息
		DeviceAmountTwoDO deviceAmountTwoinfo = deviceAmountTwoService.getProjectId(project.getId());
		if(deviceAmountTwoinfo == null){
			//保存合同金额信息
			DeviceAmountTwoDO deviceAmountTwoDO = project.getDeviceAmountTwoDO();
			deviceAmountTwoDO.setProjectId(project.getId());
			deviceAmountTwoService.save(deviceAmountTwoDO);
			saveProjectLog(project, user,"完善商务信息(二次确认)，保存合同金额信息："+deviceAmountTwoDO);
		}else{
			//更新合同金额信息
			DeviceAmountTwoDO deviceAmountTwo = project.getDeviceAmountTwoDO();
			deviceAmountTwo.setId(deviceAmountTwoinfo.getId());
			deviceAmountTwoService.update(deviceAmountTwo);
			saveProjectLog(project, user,"完善商务信息(二次确认)，保存合同金额信息："+deviceAmountTwo);
		}
	}

	/**
	 * 下拉菜单基础信息
	 * @param model
	 */
	private void getInfo(Model model){

		//1.查询项目类型
		List<ProjecttypeDO>  projecttypeDOList = projecttypeService.list(null);
		model.addAttribute("projecttypeList", projecttypeDOList);

		//查询付款方式
		List<PaytypeDO> paytypeDOList = paytypeService.list(null);
		model.addAttribute("paytypeList", paytypeDOList);

		//3.业务负责人
		List<UserDO> userDOList = userService.getlist(null);
		model.addAttribute("userList", userDOList);

		//4.业务部门
		Map<String, Object> query = new HashMap<>(16);
		List<DeptDO> sysDeptList = sysDeptService.list(query);
		model.addAttribute("deptList", sysDeptList);
		//项目阶段
		List<DictDO> dictDOList = dictService.listByType("itm_project");
		model.addAttribute("dictstatusList", dictDOList);
		//项目来源
		List<DictDO> dictSourceList = dictService.listByType("itm_project_source");
		model.addAttribute("dictSourceList", dictSourceList);

		List<CompanyDO> companyDOList = companyService.list(null);
		model.addAttribute("companyDOList", companyDOList);

		//客户名称
		List<ProjectCustnameDO> custnameDOList = projectCustnameService.list(null);
		model.addAttribute("custNameLit", custnameDOList);
	}

	/**
	 * 添加付款节点信息
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/contractconf/{id}")
	String payment(@PathVariable("id") Long id,Model model){
		ProjectDO project = projectService.get(id);
		model.addAttribute("project", project);
		this.getInfo(model);
		//查询商务信息
		DeviceAmountDO deviceAmountDO = deviceAmountService.getProjectId(id);
		model.addAttribute("deviceAmount", deviceAmountDO);
		return "itm/project/contractconf";
	}


	/**
	 * 合同确认
	 * @param project
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/contractconfirm")
	public R contractconfirm( ProjectDO project){
		UserDO user = ShiroUtils.getUser();
		project.setUserIdModified(user.getUserId());
		project.setUserNameModified(user.getName());
		project.setGmtModified(new Date());
		project.setStatus(4);
		projectService.update(project);
		saveProjectLog(project, user,"项目进入维保阶段");
		return R.ok();
	}


	/**
	 * 开始建设
	 * @param id
	 * @return
	 */
	@PostMapping( "/inprogress")
	@ResponseBody
	public R inprogress(Long id){
		ProjectDO project = new ProjectDO();
		UserDO user = ShiroUtils.getUser();
		project.setUserIdModified(user.getUserId());
		project.setUserNameModified(user.getName());
		project.setGmtModified(new Date());
		project.setStatus(4);
		project.setId(id);
		if (projectService.update(project)>0){
			saveProjectLog(project, user,"项目进入维保阶段");
			return R.ok();
		}else {
			return R.error();
		}

	}


	/**
	 * 维保信息
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/mainten/{id}")
	String mainten(@PathVariable("id") Long id,Model model){
		ProjectDO project = projectService.get(id);
		model.addAttribute("project", project);
		this.getInfo(model);
		return "itm/project/mainten";
	}


	/**
	 * 保存维保时间
	 * @param id
	 * @return
	 */
	@PostMapping( "/maintenupdate")
	@ResponseBody
	public R maintenupdate(Long id){
		ProjectDO project = new ProjectDO();
		UserDO user = ShiroUtils.getUser();
		project.setUserIdModified(user.getUserId());
		project.setUserNameModified(user.getName());
		project.setGmtModified(new Date());
		project.setStatus(5);
		project.setId(id);
		if (projectService.update(project)>0){
			saveProjectLog(project, user,"项目进入完成阶段");
			return R.ok();
		}else {
			return R.error();
		}

	}

	/**
	 * 查询所有的项目列表
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getProjectlist")
	public List<ProjectDO> getProjectlist(){
		//查询列表数据
		List<ProjectDO> projectList = projectService.list(null);
		return projectList;
	}


	/**
	 * 查询非终止的所有的项目列表
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getNotEndProjectlist")
	public List<ProjectDO> getNotEndProjectlist(){
		//查询列表数据
		List<ProjectDO> projectList = projectService.getNotEndProjectlist();
		return projectList;
	}

	/**
	 * 根据ID查询项目总金额
	 * @return
	 */
	@ResponseBody
	@GetMapping("/get/{id}")
	public ProjectDO get(@PathVariable("id") Long id){
		//查询列表数据
		ProjectDO projectDO = projectService.get(id);
		return projectDO;
	}


	@GetMapping("/uploadInfo/{id}")
	String uploadInfo(@PathVariable("id") Long id,Model model){
		ProjectDO projectDO = projectService.get(id);
		model.addAttribute("projectDO", projectDO);
		return "itm/project/uploadinfo";
	}

	@GetMapping("/ckinfo/{id}")
	public String ckinfo(@PathVariable("id") Long id,Model model){
		model.addAttribute("id", id);
		model.addAttribute("firstsrc", "/itm/project/ckedit/"+id);
		return "itm/project/ckinfo";
	}

	@GetMapping("/ckedit/{id}")
	public String ckedit(@PathVariable("id") Long id,Model model){
		ProjectDO project = projectService.get(id);
		//查询当前登录人的角色信息是否有部门经理和总经理
		int mgrcount = userService.isManagerOrCeo(getUserId());
		if(mgrcount<=0){
			if(project.getUserIdCreate() == getUserId() || project.getItmManagerId() == getUserId()){
				project.setIsmanager(1);
			}else{
				project.setIsmanager(0);
			}
		}else {
			project.setIsmanager(1);
		}
		getProjectGroup(id, project);
		model.addAttribute("project", project);
		this.getInfo(model);
		return "itm/project/edit";
	}

	private void getProjectGroup(@PathVariable("id") Long id, ProjectDO project) {
		//查询项目组成员
		Map<String, Object> params = new HashMap<>();
		params.put("projectId", id);
		List<ProjectUsersDO> projectUsersDOList = projectUsersService.list(params);
		if (projectUsersDOList != null && projectUsersDOList.size() > 0) {
			List<String> namelist = projectUsersDOList.stream().map(projectUsersDO -> projectUsersDO.getUserName()).collect(Collectors.toList());
			String userNames = String.join(",", namelist);
			project.setUserNames(userNames);
		}
	}

	@GetMapping("/getFiles/{id}")
	public String getFiles(@PathVariable("id") Long id,Model model){
//		model.addAttribute("id", id);
		ProjectDO project = projectService.get(id);
		model.addAttribute("project", project);
		this.getInfo(model);
//		return "itm/project/ckedit";
		return "itm/project/projectfiles";
	}

	@ResponseBody
	@GetMapping("/getFiles/api/{id}")
	public R getFilesApi(@PathVariable("id") Long id,Model model){
		//查询全部文件
		Map<String, Object> map = new HashMap<>();
		map.put("itmId",id);
		List<ProjectFileDO> projectFileDOList = projectFileService.list(map);
		List<Map> dataList = new ArrayList<>();
		if(projectFileDOList != null){
			for (ProjectFileDO projectFileDO:projectFileDOList) {
				Map<String, Object> m = new HashMap<>();
				m.put("updateTime", projectFileDO.getCretaTime());  // 修改时间
				m.put("isDir", 0);  // 修改时间
				m.put("url",projectFileDO.getFileName());  // 文件地址
				String filename = projectFileDO.getFileName().replace("/files/","");
				m.put("name",filename);  // 文件地址
				String contentType = null;
				String suffix = projectFileDO.getFileName().substring(projectFileDO.getFileName().lastIndexOf(".") + 1);
				contentType = new Tika().detect(projectFileDO.getFileName());
				String type=null;
				// 获取文件图标
				if ("ppt".equalsIgnoreCase(suffix) || "pptx".equalsIgnoreCase(suffix)) {
					type = "ppt";
				} else if ("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix)) {
					type = "doc";
				} else if ("xls".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix)) {
					type = "xls";
				} else if ("pdf".equalsIgnoreCase(suffix)) {
					type = "pdf";
				} else if ("html".equalsIgnoreCase(suffix) || "htm".equalsIgnoreCase(suffix)) {
					type = "htm";
				} else if ("txt".equalsIgnoreCase(suffix)) {
					type = "txt";
				} else if ("swf".equalsIgnoreCase(suffix)) {
					type = "flash";
				} else if ("zip".equalsIgnoreCase(suffix) || "rar".equalsIgnoreCase(suffix) || "7z".equalsIgnoreCase(suffix)) {
					type = "zip";
				} else if ("zip".equalsIgnoreCase(suffix) || "rar".equalsIgnoreCase(suffix) || "7z".equalsIgnoreCase(suffix)) {
					type = "zip";
				} else if (contentType != null && contentType.startsWith("audio/")) {
					type = "mp3";
				} else if (contentType != null && contentType.startsWith("video/")) {
					type = "mp4";
				}else {
					type = "file";
				}
				m.put("type", type);
				dataList.add(m);
			}
		}
		return R.ok().put("data",dataList);
	}

	@GetMapping("/itmcustName/{custname}")
	String itmcustName(@PathVariable("custname") String custname,Model model){
		model.addAttribute("custname",custname);
		return "itm/project/custname";
	}


	@ResponseBody
	@GetMapping("/custnamelist")
	public PageUtils custnamelist(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<ProjectDO> projectList = projectService.list(query);
		int total = projectService.count(query);
		PageUtils pageUtils = new PageUtils(projectList, total);
		return pageUtils;
	}



	@PostMapping("/exportData")
	@ResponseBody
	public void downloadTemplate(ProjectDO projectDO,HttpServletResponse response){
		//ProjectDO project
		Map<String, Object> params = new HashMap<>();
		if(StringUtils.isNotBlank(projectDO.getName())){
			params.put("name",projectDO.getName());
		}
		if(projectDO.getStatus() != null){
			params.put("statuse",projectDO.getStatus());
		}
		if(projectDO.getGmtCreateStr() != null){
			params.put("gmtCreateStre",projectDO.getGmtCreateStr());
		}
		if(projectDO.getGmtCreateend() != null){
			params.put("gmtCreateende",projectDO.getGmtCreateend());
		}
		if(projectDO.getGmtModifiedStr() != null){
			params.put("gmtModifiedStre",projectDO.getGmtModifiedStr());
		}
		if(projectDO.getGmtModifiedend() != null){
			params.put("gmtModifiedende",projectDO.getGmtModifiedend());
		}
		if(projectDO.getCustName() != null){
			params.put("custName",projectDO.getCustName());
		}
		//查询当前登录人的角色信息是管理层
		int mgrcount = userService.isManagerOrCeo(getUserId());
		if(mgrcount<=0) {
			params.put("createUserid",getUserId());
		}
		List<ProjectDO> projectList = projectService.list(params);
		for (ProjectDO obj:projectList) {
			setProName(obj);
		}
		ExcelUtil.exportExcel(projectList,"项目列表","项目列表",ProjectDO.class,"项目列表.xls",response);
	}

	private void setProName(ProjectDO obj) {
		switch (obj.getStatus()){
			case 1:
				obj.setStatusname("跟踪阶段");
				break;
			case 2:
				obj.setStatusname("商务阶段");
				break;
			case 3:
				obj.setStatusname("在建阶段");
				break;
			case 4:
				obj.setStatusname("维保阶段");
				break;
			case 5:
				obj.setStatusname("完成阶段");
				break;
			case 6:
				obj.setStatusname("终止项目");
				break;
			default:
				obj.setStatusname("跟踪阶段");
		}
		if(obj.getItmSource() == null){
			obj.setItmSource(4);
		}
		switch (obj.getItmSource()){
			case 1:
				obj.setItmSourceName("老客户介绍");
				break;
			case 2:
				obj.setItmSourceName("招标要求");
				break;
			case 3:
				obj.setItmSourceName("来电咨询");
				break;
			default:
				obj.setItmSourceName("其他渠道");
		}
		if(obj.getItmModel() == null){
			obj.setItmModel(2);
		}
		switch (obj.getItmModel()){
			case 1:
				obj.setItmModelName("设备");
				break;
			default:
				obj.setItmModelName("运营");
		}
	}


	/**
	 * 导出数据
	 * @param id
	 * @return
	 */
	@GetMapping("/exportinfo/{id}")
	void exportinfo(@PathVariable("id") Long id,HttpServletResponse response){
		ProjectDO project = projectService.get(id);
		Map<String, Object> map = new HashMap<>();
		map.put("complanyName",project.getComplanyName());
		map.put("datestr",project.getGmtCreate());
		map.put("itmNumber",project.getItmNumber());
		map.put("name",project.getName());
		map.put("custName",project.getCustName());
		map.put("paytypeName",project.getPaytypeName()+"");
		//查询商务信息
		DeviceAmountDO deviceAmountDO = deviceAmountService.getProjectId(id);
		if(deviceAmountDO != null){
			BigDecimal deviceAmountAll = deviceAmountDO.getDeviceAmount().add(deviceAmountDO.getInstallAmount())
					.add(deviceAmountDO.getTechAmount()).add(deviceAmountDO.getConOtherAmount());
			map.put("deviceAmountAll",deviceAmountAll);
			map.put("deviceAmount",deviceAmountDO.getDeviceAmount());
			map.put("installAmount",deviceAmountDO.getInstallAmount());
			map.put("techAmount",deviceAmountDO.getTechAmount());
			map.put("conOtherAmount",deviceAmountDO.getConOtherAmount());
			BigDecimal allPurAmount = deviceAmountDO.getCompPurPrice().add(deviceAmountDO.getOnPurPrice()).add(deviceAmountDO.getOtherPrice());
			map.put("allPurAmount",allPurAmount);
			map.put("compPurPrice",deviceAmountDO.getCompPurPrice());
			map.put("onPurPrice",deviceAmountDO.getOnPurPrice());
			map.put("otherPrice",deviceAmountDO.getOtherPrice());
			map.put("outlayPrice",deviceAmountDO.getOutlayPrice());
			map.put("outlayTax",deviceAmountDO.getOutlayTax());
			map.put("insurancePrice",deviceAmountDO.getInsurancePrice());
			map.put("outlayOtherPrice",deviceAmountDO.getOutlayOtherPrice());
			BigDecimal allManagerAmount = deviceAmountDO.getSaleExpPrice().add(deviceAmountDO.getTravelPrice()).add(deviceAmountDO.getBusinessPrice())
					.add(deviceAmountDO.getMgrPrice()).add(deviceAmountDO.getOnofficePrice()).add(deviceAmountDO.getExpressPrice()).add(deviceAmountDO.getMgrOtherPrice());
			map.put("allManagerAmount",allManagerAmount);
			map.put("saleExpPrice",deviceAmountDO.getSaleExpPrice());
			map.put("travelPrice",deviceAmountDO.getTravelPrice());
			map.put("businessPrice",deviceAmountDO.getBusinessPrice());
			map.put("mgrPrice",deviceAmountDO.getMgrPrice());
			map.put("onofficePrice",deviceAmountDO.getOnofficePrice());
			map.put("expressPrice",deviceAmountDO.getExpressPrice());
			map.put("mgrOtherPrice",deviceAmountDO.getMgrOtherPrice());
			map.put("taxCost",deviceAmountDO.getTaxCost());
			map.put("financialCosts",deviceAmountDO.getFinancialCosts());
			map.put("otherCost",deviceAmountDO.getOtherCost());
			map.put("allCost",deviceAmountDO.getAllCost());
			map.put("allprofit",deviceAmountDO.getProfit());
			if(deviceAmountDO.getAllAmount() != null && deviceAmountDO.getAllAmount().compareTo(BigDecimal.ZERO) !=0){
				BigDecimal b =deviceAmountDO.getProfit().divide(deviceAmountDO.getAllAmount(),5);
				b= b.multiply(new BigDecimal(100));
				double promarg = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				deviceAmountDO.setProfitmargin(promarg+"%");
			}else{
				deviceAmountDO.setProfitmargin("0%");
			}
			map.put("profitmargin",deviceAmountDO.getProfitmargin());
		}else {
			map.put("deviceAmountAll","");
			map.put("deviceAmount","");
			map.put("installAmount","");
			map.put("techAmount","");
			map.put("conOtherAmount","");
			map.put("allPurAmount","");
			map.put("compPurPrice","");
			map.put("onPurPrice","");
			map.put("otherPrice","");
			map.put("outlayPrice","");
			map.put("outlayTax","");
			map.put("insurancePrice","");
			map.put("outlayOtherPrice","");
			map.put("allManagerAmount","");
			map.put("saleExpPrice","");
			map.put("travelPrice","");
			map.put("businessPrice","");
			map.put("mgrPrice","");
			map.put("onofficePrice","");
			map.put("expressPrice","");
			map.put("mgrOtherPrice","");
			map.put("taxCost","");
			map.put("financialCosts","");
			map.put("otherCost","");
			map.put("allCost","");
			map.put("allprofit","");
			map.put("profitmargin","");
		}

		DeviceAmountTwoDO deviceAmountTwoDO = deviceAmountTwoService.getProjectId(id);
		if(deviceAmountTwoDO != null){

			BigDecimal deviceAmountAll = deviceAmountTwoDO.getDeviceAmount().add(deviceAmountTwoDO.getInstallAmount()).add(deviceAmountTwoDO.getTechAmount()).add(deviceAmountTwoDO.getConOtherAmount());
			map.put("deviceAmountAllTwo",deviceAmountAll);
			map.put("deviceAmountTwo",deviceAmountTwoDO.getDeviceAmount());
			map.put("installAmountTwo",deviceAmountTwoDO.getInstallAmount());
			map.put("techAmountTwo",deviceAmountTwoDO.getTechAmount());
			map.put("conOtherAmountTwo",deviceAmountTwoDO.getConOtherAmount());
			BigDecimal allPurAmount = deviceAmountTwoDO.getCompPurPrice().add(deviceAmountTwoDO.getOnPurPrice()).add(deviceAmountTwoDO.getOtherPrice());
			map.put("allPurAmountTwo",allPurAmount);
			map.put("compPurPriceTwo",deviceAmountTwoDO.getCompPurPrice());
			map.put("onPurPriceTwo",deviceAmountTwoDO.getOnPurPrice());
			map.put("otherPriceTwo",deviceAmountTwoDO.getOtherPrice());
			map.put("outlayPriceTwo",deviceAmountTwoDO.getOutlayPrice());
			map.put("outlayTaxTwo",deviceAmountTwoDO.getOutlayTax());
			map.put("insurancePriceTwo",deviceAmountTwoDO.getInsurancePrice());
			map.put("outlayOtherPriceTwo",deviceAmountTwoDO.getOutlayOtherPrice());
			BigDecimal allManagerAmount = deviceAmountTwoDO.getSaleExpPrice().add(deviceAmountTwoDO.getTravelPrice()).add(deviceAmountTwoDO.getBusinessPrice())
					.add(deviceAmountTwoDO.getMgrPrice()).add(deviceAmountTwoDO.getOnofficePrice()).add(deviceAmountTwoDO.getExpressPrice()).add(deviceAmountTwoDO.getMgrOtherPrice());
			map.put("allManagerAmountTwo",allManagerAmount);
			map.put("saleExpPriceTwo",deviceAmountTwoDO.getSaleExpPrice());
			map.put("travelPriceTwo",deviceAmountTwoDO.getTravelPrice());
			map.put("businessPriceTwo",deviceAmountTwoDO.getBusinessPrice());
			map.put("mgrPriceTwo",deviceAmountTwoDO.getMgrPrice());
			map.put("onofficePriceTwo",deviceAmountTwoDO.getOnofficePrice());
			map.put("expressPriceTwo",deviceAmountTwoDO.getExpressPrice());
			map.put("mgrOtherPriceTwo",deviceAmountTwoDO.getMgrOtherPrice());
			map.put("taxCostTwo",deviceAmountTwoDO.getTaxCost());
			map.put("financialCostsTwo",deviceAmountTwoDO.getFinancialCosts());
			map.put("otherCostTwo",deviceAmountTwoDO.getOtherCost());
			map.put("allCostTwo",deviceAmountTwoDO.getAllCost());
			map.put("allprofitTwo",deviceAmountTwoDO.getProfit());
			if(deviceAmountTwoDO.getAllAmount() != null && deviceAmountTwoDO.getAllAmount().compareTo(BigDecimal.ZERO) !=0){
				BigDecimal b =deviceAmountTwoDO.getProfit().divide(deviceAmountTwoDO.getAllAmount(),5);
				b= b.multiply(new BigDecimal(100));
				double promarg = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				deviceAmountTwoDO.setProfitmargin(promarg+"%");
			}else{
				deviceAmountTwoDO.setProfitmargin("0%");
			}
			map.put("profitmarginTwo",deviceAmountTwoDO.getProfitmargin());
		}else{
			map.put("deviceAmountAllTwo","");
			map.put("deviceAmountTwo","");
			map.put("installAmountTwo","");
			map.put("techAmountTwo","");
			map.put("conOtherAmountTwo","");
			map.put("allPurAmountTwo","");
			map.put("compPurPriceTwo","");
			map.put("onPurPriceTwo","");
			map.put("otherPriceTwo","");
			map.put("outlayPriceTwo","");
			map.put("outlayTaxTwo","");
			map.put("insurancePriceTwo","");
			map.put("outlayOtherPriceTwo","");
			map.put("allManagerAmountTwo","");
			map.put("saleExpPriceTwo","");
			map.put("travelPriceTwo","");
			map.put("businessPriceTwo","");
			map.put("mgrPriceTwo","");
			map.put("onofficePriceTwo","");
			map.put("expressPriceTwo","");
			map.put("mgrOtherPriceTwo","");
			map.put("taxCostTwo","");
			map.put("financialCostsTwo","");
			map.put("otherCostTwo","");
			map.put("allCostTwo","");
			map.put("allprofitTwo","");
			map.put("profitmarginTwo","");
		}
		String fileNmae = "项目明细";
		TemplateExportParams param = new TemplateExportParams("/excelTemplates/projectTemplants.xlsx", true);
		try {
			Workbook book = ExcelExportUtil.exportExcel(param, map);
			//下载方法
			ExcelUtil.export(response, book, fileNmae);
		} catch (Exception e) {
			System.out.println("导出模板Excel，失败:" + e);
		}
	}


	@GetMapping("/moreremove/{id}")
	String moreremove(@PathVariable("id") Long id,String salexpprice,Model model){
		ProjectDO project = projectService.get(id);
		model.addAttribute("project", project);
		model.addAttribute("salexpprice", salexpprice);
		//查询跟踪阶段、商务阶段、在建阶段
		List<ProjectDO> projectList = projectService.getProjectlistByStatus(id);
		model.addAttribute("projectList", projectList);
		return "itm/project/moreremove";
	}


	/**
	 * 删除
	 */
	@PostMapping( "/moreremoveupdate")
	@ResponseBody
	public R moreremoveupdate( ProjectDO project){
		//更新报销
		String message = "";
		DeviceAmountTwoDO deviceAmountTwoDO = deviceAmountTwoService.getProjectId(project.getOtherid());
		if(deviceAmountTwoDO != null){
			message= "从["+project.getName()+"]转移报销金额,修改人员报销："+deviceAmountTwoDO.getSaleExpPrice()+"为："+(project.getSalexpprice());
			deviceAmountTwoDO.setSaleExpPrice(project.getSalexpprice());
			deviceAmountTwoService.update(deviceAmountTwoDO);
		}else{
			deviceAmountTwoDO = new DeviceAmountTwoDO();
			deviceAmountTwoDO.setSaleExpPrice(project.getSalexpprice());
			deviceAmountTwoDO.setProjectId(project.getOtherid());
			deviceAmountTwoService.save(deviceAmountTwoDO);
			message= "从["+project.getName()+"]转移报销金额："+project.getSalexpprice()+"到本项目";
		}
		ProjectLogDO projectLogDO = new ProjectLogDO();
		projectLogDO.setGmtCreate(new Date());
		projectLogDO.setProjectId(project.getOtherid());
		projectLogDO.setUserNameCreate(getUser().getName());
		projectLogDO.setUserIdCreate(getUserId());
		projectLogDO.setRemark(message);
		projectLogService.save(projectLogDO);

		if(projectService.remove(project.getId())>0){
			//记录日志
			ProjectDO project1 = projectService.get(project.getId());
			saveProjectLog(project, getUser(),"终止项目");
			return R.ok();
		}
		return R.error();
	}


}
